package com.livepan.server.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.livepan.server.dao.CourseContentDOMapper;
import com.livepan.server.dataobject.CourseContentDO;
import com.livepan.server.dataobject.CourseContentDOExample;
import com.livepan.server.error.BusinessException;
import com.livepan.server.error.EmBusinessError;
import com.livepan.server.service.model.CourseContentModel;
import com.livepan.server.service.model.PageModel;
import com.livepan.server.utils.CopyUtil;
import com.livepan.server.utils.UUIDUtil;
import com.livepan.server.utils.ValidatorUtil;
import com.livepan.server.validator.ValidationResult;
import com.livepan.server.validator.ValidatorImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.nio.cs.CharsetMapping;


import java.util.List;
import java.util.stream.Collectors;

@Service
public class CourseContentService {
    @Autowired
    private CourseContentDOMapper courseContentDOMapper;

    @Autowired
    private ValidatorImpl validator;


    public void save(CourseContentModel courseContentModel) throws BusinessException {
        ValidationResult validateResult = validator.validate(courseContentModel);
        if (validateResult.isHasError()) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, validateResult.getErrMsg());
        }
        CourseContentDO courseContentDO = CopyUtil.copy(courseContentModel, CourseContentDO.class);
        if (courseContentDOMapper.selectByPrimaryKey(courseContentDO.getId()) == null) {
            this.insert(courseContentDO);
        } else {
            this.update(courseContentDO);
        }
    }

    private void insert(CourseContentDO courseContentDO) {
        courseContentDOMapper.insert(courseContentDO);
    }

    private void update(CourseContentDO courseContentDO) {
        courseContentDOMapper.updateByPrimaryKeyWithBLOBs(courseContentDO);
    }

    public CourseContentModel getCourseContent(String courseId) {
        CourseContentDOExample courseContentDOExample = new CourseContentDOExample();
        courseContentDOExample.createCriteria().andIdEqualTo(courseId);
        List<CourseContentDO> courseContentDOList = courseContentDOMapper
                .selectByExampleWithBLOBs(courseContentDOExample);
        if (courseContentDOList.size() == 0) {
            return null;
        } else {
            return convertCourseContentModelFromCourseContentDO(courseContentDOList.get(0));
        }
    }

    private CourseContentModel convertCourseContentModelFromCourseContentDO(CourseContentDO courseContentDO) {
        if (courseContentDO == null) {
            return null;
        }
        CourseContentModel courseContentModel = new CourseContentModel();
        BeanUtils.copyProperties(courseContentDO, courseContentModel);
        return courseContentModel;
    }
}
